<template>
  <Modal
    title="上传应用图片"
    @cancel="closeModal"
    :closable="false"
    okText="确定"
    cancelText="取消"
    :visible="visible"
    :destroy-on-close="true"
    @ok="handleOk"
  >
    <div class="p-4 m-4 border flex justify-center">
      <img class="w-300px h-200px block" :src="props.logoLink" />
    </div>
    <div class="p-4 m-4 mx-auto">
      <Upload
        class="block"
        list-type="picture"
        name="rollbackFile"
        :max-count="1"
        :before-upload="beforeUpload"
        v-model:file-list="imageFile"
        :headers="{ 'Content-Type': 'multipart/form-data' }"
        @change="handleFileChange"
      >
        <div class="mx-auto relative left-[150px]">
          <Button type="primary" shape="round" size="large">
            上传LOGO
            <UploadOutlined> </UploadOutlined>
          </Button>
        </div>
      </Upload>
    </div>
  </Modal>
</template>

<script lang="ts" setup>
import { Modal, Upload, Button } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { ref } from 'vue';
import { useMessage } from '../../../../hooks/web/useMessage';
import { updateLogo } from '../../../../api/system-mgmt/app-mgmt/app';

const emits = defineEmits(['uploadSuccess']);
const imageFile = ref([]);
const visible = ref(false);
const props = defineProps(['logoLink', 'appId']);
const { createMessage } = useMessage();

const handleOk = async () => {
  try {
    let file;
    if (imageFile.value.length === 0) {
      throw new Error('请先上传LOGO');
    } else {
      file = imageFile.value[0].originFileObj;
    }
    const res = await updateLogo(file, props.appId);
    if (res.data.isSuccess) {
      createMessage.success('LOGO上传成功');
      visible.value = false;
      emits('uploadSuccess', true);
      imageFile.value = [];
    } else {
      createMessage.error('LOGO上传失败');
    }
  } catch (error) {
    if (typeof error === 'string') createMessage.warning(error);
  }
};

const openModal = () => {
  visible.value = true;
  imageFile.value = [];
};
const closeModal = () => {
  visible.value = false;
};

const handleFileChange = (files) => {
  let newFileList = [...files.fileList];
  newFileList = newFileList.slice(-1);
  imageFile.value = newFileList;
};
defineExpose({ openModal, visible, closeModal });

const beforeUpload = () => {
  return false;
};
</script>

<style lang="less" scoped></style>
